<template>
  <!-- 优惠劵管理 -->
  <div>
    <!-- 搜索 -->
    <div>
      <el-input v-model.trim="input.title" placeholder="请输入优惠劵名称" class="sous" />

      <el-select v-model="input.type" placeholder="请选择优惠券类型" class="sous">
        <el-option label="满减卷" value="1" />
        <el-option label="全部" value />
      </el-select>
      <el-select v-model="input.status" placeholder="请选择优惠状态" class="sous">
        <el-option label="下架" value="0" />
        <el-option label="正常" value="1" />
        <el-option label="已过期" value="-1" />
        <el-option label="全部" value />
      </el-select>

      <el-button type="primary" @click="sous(input)">
        <span class="iconfont icon-icon-sousuo" style="margin-right: 10px"></span>查找
      </el-button>

      <!-- 添加对话框 -->
      <el-button type="text" @click="dialogVisible = true">
        <el-button type="primary" @click="add">
          <span class="iconfont icon-icon-B-tianjiabiji" style="margin-right: 10px"></span>添加
        </el-button>
      </el-button>

      <!-- 导出表格 -->
      <el-button type="primary" @click="exportExcel">
        <span class="iconfont icon-daochu" style="margin-right: 10px"></span>当前页导出
      </el-button>
    </div>

    <!-- 表单 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column label="优惠劵ID" prop="id" sortable align="center" />
      <el-table-column label="优惠劵名称" prop="title" align="center" />
      <el-table-column label="优惠劵类型" prop="type" width="180" align="center">
        <template #default="scope">
          <span>{{ scope.row.type == 1 ? "满减卷！" : "其他" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="介绍" prop="description" align="center" />
      <el-table-column label="优惠劵数量" prop="total" align="center" />
      <el-table-column label="剩余数量" prop="surplus" align="center" />
      <el-table-column label="每人限额" prop="limit" align="center" />
      <el-table-column label="满减金额" prop="discount" width="180" align="center">
        <template #default="scope">
          <span>减免{{ scope.row.discount }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="最低消费" prop="min" align="center">
        <template #default="scope">
          <span>满{{ scope.row.min }}元可用</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.status == 1
                ? 'success'
                : scope.row.status == 0
                ? 'danger'
                : 'info'
            "
          >{{ format(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用类目名称" prop="categoryTitle" align="center">
        <template #default="scope">
          <el-tag>
            {{
            scope.row.categoryTitle ? scope.row.categoryTitle : "全部类型"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用类目ID" prop="categoryId" align="center" />
      <el-table-column label="领卷相对天数" prop="days" align="center">
        <template #default="scope">
          <span>{{ scope.row.days ? scope.row.days : "无" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领卷开始时间" prop="gmtLastLogin" align="center">
        <template #default="scope">
          <span>
            {{
            scope.row.gmtStart ? time(scope.row.gmtStart, 1) : "无"
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="领卷结束时间" prop="gmtLastLogin" align="center">
        <template #default="scope">
          <span>{{ scope.row.gmtEnd ? time(scope.row.gmtEnd) : "无" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="140">
        <template #default="scope">
          <!-- 激活 -->
          <el-button size="small" :disabled="scope.row.status == -1" :type="scope.row.status ? 'danger' : 'primary'" @click="editStatus(scope.row)">
            {{
            scope.row.status == 1
            ? "冻结"
            : scope.row.status == 0
            ? "激活"
            : "失效"
            }}
          </el-button>
          <!-- 对话框 -->
          <el-button type="text" @click="dialogVisible = true">
            <!-- 修改按钮 -->
            <el-button size="small" type="info" @click="look(scope.row)">查看</el-button>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="600px" :before-close="handleClose">
      <!-- 内容 -->
      <el-form :inline="true" :model="addr" class="demo-ruleForm" status-icon label-width="120px" :rules="rules" ref="formName">
        <el-form-item label="优惠劵名称" prop="title">
          <el-input v-model.trim="addr.title" placeholder="优惠劵名称" :disabled="title == '查看'" />
        </el-form-item>
        <el-form-item label="优惠劵类型" prop="type">
          <el-select v-model="addr.type" :disabled="title == '查看'">
            <el-option label="满减卷" :value="1" />
            <el-option label="其他" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="介绍" prop="description">
          <el-input v-model.trim="addr.description" placeholder="介绍" :disabled="title == '查看'" />
        </el-form-item>
        <el-form-item label="优惠劵数量" prop="total">
          <el-input v-model.number="addr.total" placeholder="0" :disabled="title == '查看'" type="number">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限领" prop="limit">
          <el-input v-model.trim="addr.limit" placeholder="0" :disabled="title == '查看'" type="number">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠劵金额" prop="discount">
          <el-input v-model.trim="addr.discount" placeholder="0" :disabled="title == '查看'" type="number">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最低消费" prop="min">
          <el-input v-model.trim="addr.min" placeholder="0" :disabled="title == '查看'" type="number">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠劵状态">
          <el-select v-model="addr.status" :disabled="title == '查看'">
            <el-option label="下架" :value="0" />
            <el-option label="正常" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="有效期">
          <el-radio-group v-model="shows" :disabled="title == '查看'">
            <el-radio-button label="领卷相对天数" />
            <el-radio-button label="指定绝对时间" />
          </el-radio-group>
        </el-form-item>

        <el-form-item label=" " v-if="shows != '指定绝对时间'" prop="days">
          <el-input v-model.trim="addr.days" placeholder="0" :disabled="title == '查看'" type="number">
            <template #append>天</template>
          </el-input>
        </el-form-item>

        <el-form-item label=" " v-if="shows != '领卷相对天数'">
          <el-col :span="11">
            <el-date-picker v-model="addr.gmtStart" type="date" placeholder="优惠开始时间" style="width: 100%" :disabled="title == '查看'" @change="Starttime" />
          </el-col>
          <el-col class="text-center" :span="1" style="margin: 0 0.5rem">-</el-col>
          <el-col :span="11">
            <el-date-picker v-model="addr.gmtEnd" type="date" placeholder="优惠结束时间" style="width: 100%" :disabled="title == '查看'" @change="Endtime" />
          </el-col>
        </el-form-item>

        <el-form-item label="商品限制范围">
          <el-radio-group v-model="show" :disabled="title == '查看'">
            <el-radio-button label="全场通用" />
            <el-radio-button label="指定分类" />
          </el-radio-group>
        </el-form-item>

        <el-form-item label="优惠类目" v-if="show != '全场通用'">
          <el-cascader v-model="addr.categoryId" :options="options" clearable :show-all-levels="false" :props="props" :disabled="title == '查看'" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetForm()">取消</el-button>
        <el-button type="primary" @click="edit()" v-if="title == '创建'">确认</el-button>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <paging-vue v-bind="index" @limits="limitv" @pages="pagev"></paging-vue>
  </div>
</template>

<script>
import { post } from "@/utils/http.js"; // 引入封装工具
// 导出表单
import FileSaver from "file-saver";
import { utils, write } from "xlsx";

export default {
  data() {
    return {
      // rul: [
      //   {
      //     pattern: /^[1-9]\d*$/,
      //     message: "请您输入整数且大于0",
      //     trigger: "blur",
      //   },
      // ],
      // 表单验证
      rules: {
        title: [
          { required: true, message: "请您输入优惠券名称", trigger: "blur" },
        ],
        total: [
          { required: true, message: "请您输入优惠券数量", trigger: "blur" },
          {
            pattern: /^[1-9]\d*$/,
            message: "请您输入整数且大于0",
            trigger: "blur",
          },
        ],
        limit: [
          { required: true, message: "请您输入限领数", trigger: "blur" },
          {
            pattern: /^[1-9]\d*$/,
            message: "请您输入整数且大于0",
            trigger: "blur",
          },
        ],
        discount: [
          { required: true, message: "请您输入优惠金额", trigger: "blur" },
          {
            pattern: /^[1-9]\d*$/,
            message: "请您输入整数且大于0",
            trigger: "blur",
          },
        ],
        min: [
          { required: true, message: "请您输入优最低消费", trigger: "blur" },
          {
            pattern: /^[1-9]\d*$/,
            message: "请您输入整数且大于0",
            trigger: "blur",
          },
        ],
        days: [
          { required: true, message: "请您输入天数", trigger: "blur" },
          {
            pattern: /^[1-9]\d*$/,
            message: "请您输入整数且大于0",
            trigger: "blur",
          },
        ],
      },

      // 分页
      index: {
        page: 1, // 分页
        limit: 10, // 每页显示条数
        total: 10, // 总数
      },
      // 输入框
      input: {
        title: "", // 优惠劵标题
        type: null, // 优惠卷类型
        status: null, // 优惠卷状态
      },
      title: "创建",

      // 弹框数据
      addr: {
        title: "", // 优惠劵标题
        type: "", // 优惠劵类型
        description: "", // 介绍
        total: "", // 优惠劵数量
        limit: "", // 每人限领
        discount: "", // 优惠劵金额
        min: "", // 最低消费
        status: "", // 优惠劵状态
        days: "", // 有效期
        daysv: "", // 有效期
        gmtStart: "", // 优惠开始时间
        gmtEnd: "", // 优惠结束时间
        categoryId: "", // 商品分类
      },
      show: "全场通用",
      shows: "领卷相对天数",
      // 清空
      adds: {
        title: "", // 优惠劵标题
        type: "", // 优惠劵类型
        description: "", // 介绍
        total: "", // 优惠劵数量
        limit: "", // 每人限领
        discount: "", // 优惠劵金额
        min: "", // 最低消费
        status: "", // 优惠劵状态
        days: "", // 有效期
        gmtStart: "", // 优惠开始时间
        gmtEnd: "", // 优惠结束时间
        categoryId: "", // 商品分类选中
      },
      tableData: [], // 数据
      dialogVisible: false, // 弹出框显示/隐藏
      props: {
        checkStrictly: true, // 原点
        value: "id",
        label: "title", // 显示值
        children: "childrenList",
        emitPath: false,
      },
      title: "创建",
      options: [], // 优惠类目数据
      exetimes: "",
    };
  },
  created() {
    this.record(); // 调用管理者数据接口
  },
  methods: {
    // 时间戳
    time(value) {
      // 时间戳转换日期格式方法
      const date = new Date(value);
      const y = date.getFullYear(); // 年
      const MM = date.getMonth() + 1; // 月
      const d = date.getDate(); // 日
      const h = date.getHours(); // 时
      const m = date.getMinutes(); // 分
      const birthday = `${y}-${MM}-${d}-${h}:${m}`;
      this.exetimes = `${y}年${MM}月${d}日`;
      return birthday;
    },

    Starttime(item) {
      // 已有一个中国标准时间，现在可以获取其时间戳
      const today = new Date(item);
      // 获取其时间戳(单位：毫秒，通过/1000转换为秒)
      const timestap = today.getTime();
      this.addr.gmtStart = timestap;
    },
    Endtime(item) {
      // 已有一个中国标准时间，现在可以获取其时间戳
      const today = new Date(item);
      // 获取其时间戳(单位：毫秒，通过/1000转换为秒)
      const timestap = today.getTime();
      this.addr.gmtEnd = timestap;
    },

    // 导出表单
    exportExcel() {
      const wb = utils.table_to_book(document.querySelector(".el-table"));
      const wbout = write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "优惠劵" + this.exetimes + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined");
      }
      return wbout;
    },

    // 状态
    format(status) {
      if (status === 0) {
        return "下架";
      } else if (status === 1) {
        return "正常";
      } else if (status < 0) {
        return "已过期";
      }
    },

    // 数据
    record() {
      const data = {
        _gp: "admin.coupon", // 请求参数
        _mt: "list", // 请求参数
        title: this.input.title, // 优惠劵名称
        type: this.input.type, // 优惠劵类型
        status: this.input.status, // 优惠劵状态
        pageNo: this.index.page,
        limit: this.index.limit,
      };
      post(data).then((res) => {
        if (200 == res.data.errno) {
          this.tableData = res.data.data.items; // 数据
          this.index.total = res.data.data.total; // 分页总数
          for (let j = 0; j < this.tableData.length; j++) {
            if (this.tableData[j].gmtEnd < new Date().getTime()) {
              this.tableData[j].status = -1;
            }
          }
        } else {
          ElMessage.error(res.data.errmsg);
        }
      });
    },

    // 搜索
    sous() {
      this.record(); // 调用管理者数据接口
    },

    // 激活冻结
    editStatus(row) {
      if (row.gmtEnd < new Date().getTime()) {
        row.status = -1;
      } else if (row.status === 0) {
        row.status = 1;
      } else if (row.status === 1) {
        row.status = 0;
      }

      const data = {
        _gp: "admin.coupon", // 请求参数
        _mt: "updateCouponStatus", // 请求参数
        id: row.id, // 信息
        status: row.status, // 状态
      };
      post(data).then((res) => {
        if (res.data.errno == 200) {
          if (row.status === 1) {
            ElMessage.success("激活成功");
          } else if (row.status == -1) {
            ElMessage.error("已过期请勿重复点击！");
          } else {
            ElMessage.error("冻结成功");
          }
          this.record();
        } else {
          ElMessage.error(res.data.errmsg);
        }
      });
    },

    // 弹框
    handleClose(done) {
      this.$refs.formName.resetFields();

      ElMessage({
        type: "info",
        message: "取消操作！",
      });
      (this.dialogVisible = false), this.record();
    },

    // 取消
    resetForm() {
      this.$refs.formName.resetFields();
      ElMessage({
        type: "info",
        message: "取消操作！",
      });
      this.dialogVisible = false;
      Object.assign(this.addr, this.adds);
      this.show = "全场通用";
      this.shows = "领卷相对天数";
    },

    // 查看
    look(row) {
      if (row.categoryId) {
        this.show = "指定分类";
      } else {
        this.show = "全场通用";
      }

      if (row.days) {
        this.shows = "领卷相对天数";
      } else {
        this.shows = "指定绝对时间";
      }
      this.category(); // 调用类目接口
      Object.assign(this.addr, row);
      this.title = "查看";
      this.dialogVisible = true; // 弹出框显示/隐藏
    },

    // 添加弹框
    add() {
      this.show = "全场通用";
      this.shows = "领卷相对天数";
      this.title = "创建";
      this.dialogVisible = true; // 弹出框显示/隐藏
      Object.assign(this.addr, this.adds);
      this.category(); // 调用类目接口
    },
    // 添加接口
    edit() {
      this.$refs.formName.validate((valid) => {
        if (valid) {
          const data = {
            _gp: "admin.coupon",
            _mt: "create",
            ...this.addr,
          };
          post(data).then((res) => {
            if (res.data.errno == 200) {
              ElMessage.success("添加成功");
              this.dialogVisible = false; // 弹出框显示/隐藏
              this.$refs.formName.resetFields()
              this.record();
            } else {
              ElMessage.error(res.data.errmsg);
            }
          });
        } else {
        }
      });
    },

    // 类目
    category() {
      // 避免重复加载
      if (this.options.length === 0) {
        const data = {
          _gp: "category", // 请求参数
          _mt: "categoryList", // 请求参数
        };
        post(data).then((res) => {
          if (res.data.errno == 200) {
            this.options = res.data.data; // 数据
          } else {
            ElMessage.error(res.data.errmsg);
          }
        });
      }
    },

    // 分页
    limitv(e) {
      this.index.limit = e;
      this.record();
    },
    pagev(e) {
      this.index.page = e;
      this.record();
    },
  },
};
</script>

<style lang="less" scoped>
// 输入框
.el-input {
  width: 350px;
}

// 搜索
.sous {
  width: 13%;
  margin-right: 15px;
  margin-bottom: 15px;
}
</style>
